<?php

namespace StarCloud\Library\Sdk;

use Framework\DiServices\HttpClient;
use Phalcon\Di;
use StarCloud\Library\Exception;

class BaiduNovel
{
    /* @var $httpClient HttpClient */
    private $httpClient;
    private $cacheClass;
    private $token = 'baidu_novel_98aae5ad246827ef';
    private $supplier_id = "42";
    private $app_id = 'tt2d495bf4b2799b4101';

    public function __construct($config = [])
    {
        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
        $this->client_key = $config['client_key'] ?? "awg1hfaffbac94e3";
        $this->client_secret = $config['client_secret'] ?? "16bb95421d67fdbd4ffef97bcbbbde41";
    }

    protected function sign($body)
    {
        $body['app_code'] = "douyin_supplier";
        $body['time'] = time();
        $body['supplier_id'] = $this->supplier_id;
        $body['sign'] = md5( $body['app_code'] . $body['time'] . $this->token);

        return $body;
    }

    public function getBookInfo($bookId)
    {
        $url = "https://novelapi.baidu.com/third/douyin/bookinfo?";

        $body['data'] = json_encode([
            "app_id" => $this->app_id,
            "book_id" => $bookId,
            "invite_code" => "",
        ]);
        $body = $this->sign($body);

        $response = $this->httpClient->sendGetRequest($url . http_build_query($body));

        $json = json_decode($response->getBody()->getContents(), true);

        if(isset($json['errno']) && $json['errno'] == 0) {
            return $json['data']['book_info'];
        }

        return false;
    }

    public function getBookList($page, $size)
    {
        $url = "https://novelapi.baidu.com/third/douyin/booklist?";

        $body['data'] = json_encode([
            "app_id" => $this->app_id,
            "page" => $page,
            "page_size" => $size,
        ]);
        $body = $this->sign($body);

        var_dump($body);

        $response = $this->httpClient->sendGetRequest($url . http_build_query($body));

        $json = json_decode($response->getBody()->getContents(), true);

        return $json;
    }
}